<template>
  <AuFormModal
    ref="formModalRef"
    v-model="showModal"
    :title="t(title)"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 460
    }"
    :formProps="{
      class: '!w-[446px]'
    }"
    @handleConfirm="handleConfirm"
  />
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import { computed, nextTick, ref, watch } from "vue";
import { cloneDeep } from "lodash-unified";
import { ElMessage } from "element-plus";
import { tagAdd, tagUpd } from "@/api/cabinet/formulaDetail";
import { useI18n } from "vue-i18n";

interface Props {
  modelValue: boolean;
  formData: Object;
}

const props = defineProps<Props>();
const { t } = useI18n();
const emits = defineEmits(["update:modelValue", "confirm"]);
const title = ref("");
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula_detail.tag_name",
    placeholder: "formula_detail.tag_name_placeholder",
    required: true
  },
  {
    type: "input",
    key: "note",
    label: "formula_detail.tag_note",
    placeholder: "formula_detail.tag_note_placeholder",
    inType: "textarea"
  }
]);
const selfFormData = ref({});
const formModalRef = ref();

const handleConfirm = async (data: any) => {
  let service = tagAdd;
  if (data?.id) {
    service = tagUpd;
  }
  const res = await service(data);
  if (res.code == 200) {
    ElMessage({
      message: data?.id
        ? t("formula_detail.edit_tag_success")
        : t("formula_detail.add_tag_success"),
      type: "success"
    });
    formModalRef.value.reset();
    emits("update:modelValue", false);
    emits("confirm");
  }
};

watch(
  () => [props.modelValue, props.formData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as { [key: string]: any };
      title.value = rowData?.id
        ? "formula_detail.edit_tag"
        : "formula_detail.add_tag";
      if (rowData?.id) {
        nextTick(() => {
          formModalRef.value.setFormData(row);
          formModalRef.value.setFormProps("copyVersion", { hidden: true });
        });
      } else {
        nextTick(() => {
          // getVersionList();
        });
      }
    }
  }
);
</script>
